package com.bs.jianli.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.bs.jianli.entity.Menu;
import com.bs.jianli.entity.Role;
import com.bs.jianli.entity.User;
import com.bs.jianli.service.IMenuService;
import com.bs.jianli.service.IRoleService;
import com.bs.jianli.service.IUserService;
import com.bs.jianli.util.exception.NotUserException;
import com.bs.jianli.util.security.LoginUser;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author 小姚
 * @pakeageName:com.bs.jianli.service.impl
 * @ClassName:UserDetailServiceImpl
 * @Descirption:
 * @data 2023/1/13 23:52
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {



    @Resource
    IUserService service;

    @Resource
    IRoleService roleService;

    @Resource
    IMenuService menuService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(StringUtils.isBlank(username)){
            throw new NotUserException("用户名不能为空");
        }
        LambdaQueryWrapper<User> lq=new LambdaQueryWrapper<>();
        lq.eq(User::getUsername,username);
        User user = service.getOne(lq);
        List<Role> roles = roleService.addRoles(user.getUserid());
        user.setRoles(roles);
        List<Menu> menus = menuService.byMenus(user.getUserid(),"0");
        user.setMenus(menus);
        List<String> pression = menuService.byPression(user.getUserid());
        Set<String> sets=new HashSet<>(pression);
        user.setPression(sets);
        if(user==null){
            throw new NotUserException("用户名或密码错误");
        }
        LoginUser loginUser=new LoginUser(user);

        return loginUser;
    }
}
